/*
 * Copyright (c) 2005-2007 by Platform Computing Corporation.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Platform Computing, Inc. You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the
 * license agreement you entered into with Platform.
 *
 * Author     sxu
 * Created    Aug 2, 2007
 * Version    $Id: DefaultOutputReader.java,v 1.1 2010/02/24 02:32:24 yongdu Exp $
 */

package com.wms.execcmd;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;

/**
 *
 */
public class DefaultOutputReader implements ICommandOutputReader {

	/** Logging handler */
	private Logger logger = null;
	private StringBuffer buffer = new StringBuffer();
	private final static String DEFAULT_CHARSET = "UTF-8";
	private final static int BUFFER_SIZE = 1024;
	private String charset = null;

	public DefaultOutputReader(Logger logger) {
		this(logger, null);
	}

	public DefaultOutputReader(Logger logger, String charset) {
		this.charset = charset == null ? DEFAULT_CHARSET : charset;
		this.logger = logger;
	}

	/**
	 * @see com.wms.execcmd.perf.dataloader.ego.shellscript.ICommandOutputReader#read(java.io.InputStream)
	 */
	public void read(InputStream input) throws IOException {
		BufferedReader reader = null;
		char[] buff = new char[BUFFER_SIZE];
		int len = 0;
		try {
			reader = new BufferedReader(new InputStreamReader(input, charset));
			while ((len = reader.read(buff)) > 0) {
				this.buffer.append(buff, 0, len);
			}

			if (this.logger.isDebugEnabled()) {
				this.logger.debug(this.buffer);
			}
		}
		finally {
			if (reader != null) {
				try {
					reader.close();
					reader = null;
				}
				catch (Exception ex) {
					// Do nothing
				}
			}
		}
	}

	public StringBuffer getBuffer() {
		return buffer;
	}

	public void cleanBuffer() {
		this.buffer.setLength(0);
	}

}
